package xyf.p10.dp;

import java.util.Arrays;

/**
 * ClassName: P0322_CoinChange
 * Description:
 * Author: xyf
 * Date: 9/9/22 10:28 AM
 * Version: 1.0
 **/
public class P0322_CoinChange
{
    public int coinChange(int[] coins, int amount)
    {
        int[][] dp = new int[coins.length][amount + 1];
        for (int i = 0; i < coins.length; i++)
        {
            for (int j = 0; j < amount + 1; j++)
            {
                dp[i][j] = Integer.MAX_VALUE;
            }
        }

        for (int i = 0; i * coins[0] <= amount; i++)
        {
            dp[0][i * coins[0]] = i;
        }

        for (int i = 1; i < coins.length; i++)
        {
            for (int j = 0; j < amount + 1; j++)
            {
                int cnt = j / coins[i];
                for (int k = 0; k <= cnt; k++)
                {
                    if (dp[i - 1][j - k * coins[i]] != Integer.MAX_VALUE && dp[i - 1][j - k * coins[i]] + k < dp[i][j])
                        dp[i][j] = dp[i - 1][j - k * coins[i]] + k;
                }
            }
        }
        return dp[dp.length - 1][amount] == Integer.MAX_VALUE ? -1 : dp[dp.length - 1][amount];
    }
}